package fun.stgoder.dev.listener.sdk;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import fun.stgoder.dev.listener.common.Constants;
import fun.stgoder.dev.listener.common.FaceHttpApi;
import fun.stgoder.dev.listener.udp.UdpServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Date;

public class FaceMsgTask implements Runnable {
    private Logger logger = LoggerFactory.getLogger(FaceMsgTask.class);

    private FaceMsg msg;

    public FaceMsgTask(FaceMsg msg) {
        this.msg = msg;
    }

    @Override
    public void run() {
        String snapFaceId = IdUtil.objectId();
        String snapFaceFileDirPath = Constants.SNAP_FACE_PATH + File.separator + DateUtil.format(new Date(), "yyyy-MM-dd");
        File snapFaceFileDir = new File(snapFaceFileDirPath);
        if (!snapFaceFileDir.exists())
            snapFaceFileDir.mkdirs();
        String snapFaceFilePath = snapFaceFileDirPath + File.separator + snapFaceId + ".jpg";
        File snapFaceFile = new File(snapFaceFilePath);
        FileUtil.writeBytes(msg.getSmallFileBytes(), snapFaceFile);
        msg.setSmallFileBytes(null);
        msg.setSnapFaceId(snapFaceId);

        /*Long prisonerId = FaceHttpApi.findWho(new File(Constants.SNAP_FACE_PATH +
                File.separator + DateUtil.format(new Date(msg.getEts()), "yyyy-MM-dd") +
                File.separator + msg.getSnapFaceId() + ".jpg"));*/
        String faceId = FaceHttpApi.findWho2(new File(Constants.SNAP_FACE_PATH +
                File.separator + DateUtil.format(new Date(msg.getEts()), "yyyy-MM-dd") +
                File.separator + msg.getSnapFaceId() + ".jpg"));
        if (faceId == null) {
            snapFaceFile.delete();

            return;
        }
        msg.setFaceId(faceId);

        //msg.setPrisonerId(prisonerId);

        String msgJson = JSONUtil.toJsonStr(msg);
        logger.debug(msgJson);
        UdpServer.instance.send(msgJson.getBytes(), Constants.SERVER_UDP_ADDRESS);

        this.msg = null;
    }
}
